package net.zjitc.controller;


import net.zjitc.pojp.User;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Created by asus on 2017/12/3.
 */
@WebServlet(name = "AjaxServlet",urlPatterns = "/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username = ?";
        User user = null;
        try {
            user = (User) runner.query(sql,new BeanHandler(User.class),username);
            if(user != null){//存在
                //response.getWriter().print("<span style=\"color: red;\">用户名已存在</span>");
                response.getWriter().print(true);//给前端相应，状态
            }else{//不存在
                response.getWriter().print(false);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
